package Test_0119;

/**
 * Created with Intellij IDEA
 * Description:
 * User: 星辰
 */
public class BinarySearchTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int val){
            this.val=val;
        }
    }
    public TreeNode root;
    //插入
    public void insert(int key){
           if(root==null){
               root=new TreeNode(key);
               return ;
           }
           TreeNode parent=null;
           TreeNode cur=root;
           TreeNode node=new TreeNode(key);
        while(cur!=null){
            if(key< cur.val){
                parent=cur;
                cur=cur.left;
            }else if(key>cur.val){
                parent=cur;
                cur=cur.right;
            }else{
                return;
        }
        if(key< parent.val){
            parent.left=node;
        }else if(key>cur.val){
            parent.right=node;
        }
    }
    }
    //查找
    public TreeNode search(int val){
        //小于在左子树；
        //大于在右子树
        TreeNode cur=root;
        while(cur!=null){
        if(val< cur.val){
            cur=cur.left;
        }else if(val>cur.val){
            cur=cur.right;
        }else{
            return cur;
        }
        }
        return null;
    }
    //删除
    //1.找到节点，
    //2.删除节点
    public void remove(int  key){
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null){
            if(key< cur.val){
                parent=cur;
                cur=cur.left;
            }else if(key>cur.val){
                parent=cur;
                cur=cur.right;
            }else{
                removeKey(parent,cur);
                return;
            }
    }
    }
    public void removeKey(TreeNode parent,TreeNode cur){
        //左树为空
        if(cur.left==null){
            if(cur==root) {
                root = cur.right;
            }else{
                if(cur==parent.left){
                    parent.left=cur.right;
                }else{
                    parent.right=cur.left;
                }
            }
        }else if(cur.right==null){
            if(cur==root){
                root=cur.left;
            }else{
                if(cur==parent.left){
                    parent.left=cur.left;
                }else{
                    parent.right=cur.right;
                }
            }
        }else{
            TreeNode c=cur;
            if(cur==parent.left){
                while(c!=null){
                    parent=c;
                    c=c.right;
                }
                parent.val=c.val;
            }else{
                while(c!=null){
                    parent=cur;
                    c=c.left;
                }
                parent.val=c.val;
            }

        }
    }
}
